//读取配置文件，变量config的类型是Object类型
const config = require('./config');
// 用户获取签名的函数
const sign = require('./sign.js');
const db = uniCloud.database()

// 发送模板消息
async function WeixinMessagePush(params){
	let access_token=await getToken()
	let data= {
           "touser":params.openid,
           "template_id":"Rql-hWyHqZjyf0aHUNttsk62S-zNgpW0yB1yet8qKzo",
           "url":"http://vlog.minihack.cn",            
           "data":{
                   "nickname": {
                       "value":params.nickname,
                       "color":"#173177"
                   }
           }
       }
	let access_tokenApiUrl =
		`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`
	let pushRes = await uniCloud.httpclient.request(access_tokenApiUrl, {
		method: 'POST',
		data:JSON.stringify(data),
		dataType: 'json'
	})
}

// 获取签名
async function getSignature(params) {
	// 1.获取ticket--
	let jsapi_ticket = ''
	let cloudTicket = await db.collection('jsapi_ticket').orderBy("expires_in", "asc").limit(1).get()
	// 查看jsapi_ticket是否过期
	if (cloudTicket.data.length > 0 && parseInt(cloudTicket.data[0].expires_in) > parseInt(new Date().getTime() / 1000)) {
		jsapi_ticket = cloudTicket.data[0].jsapi_ticket
	} else {
		var tokenApiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		// 获取token
		let getToken = await uniCloud.httpclient.request(tokenApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = getToken.data.access_token
		// 获取Ticket
		var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
		let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		// 拿到最新的票据
		jsapi_ticket = getTicket.data.ticket
		let expires_in = parseInt(new Date().getTime() / 1000) + parseInt(getTicket.data.expires_in)
		// 存到数据库
		if (cloudTicket.data.length > 0) {
			await db.collection('jsapi_ticket').doc(cloudTicket.data[0]._id).update({
				jsapi_ticket,
				expires_in
			})
		} else {
			await db.collection('jsapi_ticket').add({
				jsapi_ticket,
				expires_in
			})
		}
	}
	// 获取签名
	let signature = sign(jsapi_ticket, params.url)
	signature.appId = config.appid
	return signature
}

// 通过appid 和 AppSecret 获取token 
async function getToken() {
	let access_token = ''
	// 通过appid 和 scret 获取微信服务器的access_token
	// 判断服务器是否存有access_token并且还没有过期
	// 如果过期，则从新获取
	// 未过期，直接返回服务器保存的token
	let cloudToken = await db.collection('wx_token').orderBy("expires_in", "asc").limit(1).get()
	if (cloudToken.data.length > 0 && parseInt(cloudToken.data[0].expires_in) > parseInt(new Date().getTime() / 1000)) {
		access_token = cloudToken.data[0].access_token
	} else {
		let apiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		const res = await uniCloud.httpclient.request(apiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		access_token = res.data.access_token
		if (!access_token) {
			return {
				msg: 'token不存在或已经达到最高限度'
			}
		}
		let expires_in = parseInt(new Date().getTime() / 1000) + parseInt(res.data.expires_in)
		// 存到数据库
		if (cloudToken.data.length > 0) {
			await db.collection('wx_token').doc(cloudToken.data[0]._id).update({
				access_token,
				expires_in
			})
		} else {
			await db.collection('wx_token').add({
				access_token,
				expires_in
			})
		}
	
	}
	return access_token
}

// 获取票据
async function getTicket() {
	let token =await getToken()
	// 获取Ticket
	var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
	let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
		method: 'POST',
		data: {},
		dataType: 'json'
	})
	let jsapi_ticket = getTicket.data.ticket
	return getTicket
}

// 微信公众号登录
async function login(params) {
	// 判断 通过code到数据库获取 openid 和 access_token expries_in
	// 如果过期-返回重新获取 code-在进行以上操作
	// 如果没有获到数据--// 直接获取 openid access_token expries_in
	// 保存 数据到数据库{code,openid,access_token,expries_in} 
	// 获取用户信息--将用户信息添加到以上的表中
	// 返回用户信息
	let result=''
	let code = params.code
	if (!code) {
		return {
			msg: 'code不存在',
			data: false
		}
	}
	// 1.通过code获取access_token和openid 
	let access_tokenApiUrl =
		`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.appid}&secret=${config.appsecret}&code=${code}&grant_type=authorization_code`
	let access_tokenRes = await uniCloud.httpclient.request(access_tokenApiUrl, {
		method: 'POST',
		data: {},
		dataType: 'json'
	})
	let {
		access_token,
		openid,
		expires_in
	} = access_tokenRes.data
	// 判断用户是否存在--存在则返回用户信息--不存在则进行下一步
	let userInfoRes = await db.collection('wxuser').where({
		openid: openid
	}).get()
	if(userInfoRes.data.length===0){
		// 2.使用access_token和openId 获取用户信息
		let userinfoApiUrl =
			`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
		let userinfoRes = await uniCloud.httpclient.request(userinfoApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		// 将用户信息保存都数据库
		let data = access_tokenRes.data
		// 用于后期判断access_token是否过期
		data.expires_in = parseInt(new Date().getTime() / 1000) + expires_in
		let addRes = await db.collection('wxuser').add({
			...data,
			...userinfoRes.data
		})
		result = await db.collection('wxuser').doc(addRes.id)
	}else{
		result=userInfoRes
	}
	// 发送登录成功模板消息
	params.openid= result.data[0].openid
	params.nickname= result.data[0].nickname
	await WeixinMessagePush(params)
	return {
		status: 200,
		data: result.data[0]
	}
}

module.exports = {
	login,
	getTicket,
	getToken,
	getSignature,
	WeixinMessagePush,
}
